package com.elangzhi.ssm.task;

import com.alibaba.fastjson.JSONObject;
import com.elangzhi.ssm.model.OrderFrom;
import com.elangzhi.ssm.model.Shop;
import com.elangzhi.ssm.model.User;
import com.elangzhi.ssm.modules.orderFrom.services.OrderFromService;
import com.elangzhi.ssm.modules.shop.services.ShopService;
import com.elangzhi.ssm.modules.user.services.ThinksService;
import com.elangzhi.ssm.modules.user.services.UserService;
import org.apache.log4j.Logger;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 订单定时器
 * Created by Administrator
 */
@Component
public class OrderFromTask {

    private Logger logger = Logger.getLogger(this.getClass());

    /**
     * 查询已下单未付款的订单，超过30分钟的标注为已过时
     * 一分钟一次
     * fixedDelay 上一次任务执行结束到下一次的时间
     */
    @Scheduled(fixedDelay = 1000 * 60)
    public void checkTimeOut() {

        List<OrderFrom> orderFromList = orderFromService.listByTimeOut();
        if (orderFromList != null) {
            for (OrderFrom orderFrom : orderFromList) {
                try {
                    orderFrom.setStatus(0);
                    orderFromService.updateById(orderFrom);
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("处理超时未付款订单失败！订单号：" + orderFrom.getId());
                }
            }
        }

    }

    /**
     * 超过10天未确认收货的自动确认收货
     * 每小时一次
     * fixedDelay 上一次任务执行结束到下一次的时间
     */
    @Scheduled(fixedDelay = 1000 * 60 * 60)
    public void listByFinishOut() {

        List<OrderFrom> orderFromList = orderFromService.listByFinishOut();
        if (orderFromList != null) {
            for (OrderFrom of : orderFromList) {
                try {
                    JSONObject jsonObject;
                    if(!of.getShopId().equals(888888l)){
                        Shop shop = shopService.selectById(of.getShopId());
                        User user = userService.selectById(shop.getUserId());
                        jsonObject = thinksService.zhuanzhang("888888",user.getThinksId(),of.getPrice().toString());
                        if(!jsonObject.getBoolean("state")){
                            logger.error("自动确认收货失败！订单号：" + of.getId());
                            continue;
                        }
                    }
                    of.setStatus(4);
                    orderFromService.updateById(of);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }

    //----------------------------------------- service ---------------------------------------

    @Resource
    private UserService userService;

    @Resource
    private ShopService shopService;

    @Resource
    private ThinksService thinksService;

    @Resource
    private OrderFromService orderFromService;
}
